Skip to main content

Sets, Maps, and their Weak Versions

Using Set

// initiate
let colors = new Set();

// add
colors.add( 'red' );
colors.add( 'green' );
colors.add( 'red' ); // duplicate elements are added only once
console.log( colors ); // Set {"red", "green"}

// size
console.log( 'Size: ' + colors.size ); // 2

// has
console.log( 'has green: ' + colors.has( 'green' ) + '\nhas blue: ' + colors.has( 'blue' ) ); // true false

// delete
colors.delete( 'green' ) // true
colors.delete( 'green' ) // false

let moreColors = new Set( ['red', 'blue', 'red', 'orange'] );
console.log( moreColors ); // Set { 'red', 'blue', 'orange' }

Iterating Sets

let mySet = new Set()
mySet.add('first')
mySet.add('second')

mySet.forEach(s=>console.log(s))

for(let s of mySet) console.log(s)

console.log([... mySet])

ES6 Maps

let animal = new Map();
animal.set( 8, 'Chocolate' )
animal.set( 3, 'Filippone' )
// also chainable
animal.set( 1, 'first' ).set( 2, 'second')
// Using arrays of key-value pairs works as follows:
let newHorses = new Map( [[ 1, 'hello' ], [ 2, 'world' ]] )
// get size
console.log(animal.size)
// contains a key?
console.log(animal.has(1))
// delete item by key
animal.delete(1)

Iterating Maps

// The order in forEach block is value, key
horses.forEach( ( value, key ) => console.log( value, key ) )
// But the order in for of block is key,value
for ( let [ key, value ] of horses ) console.log( key, value )
// spread operators
console.log( [...horses] );

Weak Sets

tip

Sets and maps hold a reference of their values. This means that the garbage collector won’t be able to collect the values in sets, and key-value pairs in maps to free some memory.

This is where weak sets and maps come into play. They only hold weak references to their values, allowing garbage collection of the values while they are members of a set or map.

let firstElement = { order: 1 }, secondElement = { order: 2 }
let ws = new WeakSet( [ firstElement, secondElement ] )

console.log('has firstElement: '+ws.has( firstElement ))
//> true
delete firstElement;
// firstElement is removed from the weak set, but the result is still true,
// because even the reference object was collected by the garbage collection
// but we still can access this object.
console.log('has firstElement: '+ws.has( firstElement ))

Weak Maps

tip

Weak maps have object keys, and arbitrary values. When all strong references to a key are removed, the key is garbage collected, and the key-value pair is removed from the weak map.

Only the keys of weak maps are weak. Values placed in a weak map have strong references in the map.

let firstElement = { order: 1 }, secondElement = { order: 2 }
let wm = new WeakMap()

wm.set( firstElement, 1 )
wm.set( secondElement, {} )

console.log(wm.get( secondElement ))
//> {}

delete secondElement
// secondElement is removed from the weak map
console.log(wm)